package com.yearEndWorkload.listen;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yearEndWorkload.mapper.OutstandingChildMapper;
import com.yearEndWorkload.mapper.OutstandingPerformanceMapper;
import com.yearEndWorkload.mapper.TypeStandardMapper;
import com.yearEndWorkload.pojo.entity.OutstandingChild;
import com.yearEndWorkload.pojo.entity.OutstandingPerformance;
import com.yearEndWorkload.pojo.excel.importTemplate.NewOutstandingExcel;
import com.yearEndWorkload.pojo.vo.BaseOutstandingTreeVo;
import com.yearEndWorkload.pojo.vo.OutstandingPerformanceVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 不建议交给spring管理。
 * 交给spring管理之后会变成全局的固定的资源。若是同时出现多个管理员一起导入，就会出现错误。
 * 项目负责人的记录必须出现在表中，才可进行判断。
 */
//涉及到两个表的操作。一个是子表，一个是父表
@Data
@Slf4j
public class NewOutstandingListener implements ReadListener<NewOutstandingExcel> {

    private static final int BATCH_COUNT = 100;
    //================需要使用set方法注入下列内容==============================//
    private OutstandingChildMapper outstandingChildMapper;
    private OutstandingPerformanceMapper outstandingPerformanceMapper;

    //------------------------------------------------------//
    private TypeStandardMapper typeStandardMapper;
    //excel表缓存，可不使用，减少内存占有。
//    private List<NewOutstandingExportExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    //存入数据库的缓存信息。
    private List<OutstandingPerformance> outstandingPerformanceList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<OutstandingChild> outstandingChildList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    //记录 父id 和 项目负责人之间的映射关系
    private Map<String, Integer> mapForParent = new HashMap<>();

    //保存未正确保存的数据。
    private List<NewOutstandingExcel> unSave = new ArrayList<>();

    //保存的信息。
    private List<BaseOutstandingTreeVo> outstandingTreeVoList;

    //判断是否存在父
    private boolean isLiveNewOutstandingParent(OutstandingPerformance outstandingPerformance ) {

        QueryWrapper<OutstandingPerformance> queryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();
        map.put("year",outstandingPerformance.getYear());
        map.put("workload_type",outstandingPerformance.getWorkloadType());
        map.put("project_context",outstandingPerformance.getProjectContext());
        map.put("score",outstandingPerformance.getScore());
        map.put("responsible_person",outstandingPerformance.getResponsiblePerson());

        queryWrapper.allEq(map);


        boolean exists = outstandingPerformanceMapper.exists(queryWrapper);

        return !exists;
    }

    //判断是否存在子
    private boolean isLiveNewOutstandingChild() {

        return true;
    }


    //查询判断较比，存在一摸一样的年终业绩情况就不允许导入。


    @Override
    public void invoke(NewOutstandingExcel newOutstandingExcel, AnalysisContext analysisContext) {

        System.out.println("1");

        log.info("解析到一条有效数据:{}", JSON.toJSONString(newOutstandingExcel));
        //采用先存父表的策略。
        if (newOutstandingExcel != null) {

            String teacherName = newOutstandingExcel.getTeacherName();
            String responsiblePerson = newOutstandingExcel.getResponsiblePerson();
            if (teacherName.equals(responsiblePerson)) {
                //构造父表插入元素
                OutstandingPerformance outstandingPerformance = new OutstandingPerformance();
                outstandingPerformance.setYear(newOutstandingExcel.getYear());
                outstandingPerformance.setWorkloadType(newOutstandingExcel.getWorkloadType());
                outstandingPerformance.setProjectContext(newOutstandingExcel.getProjectContext());
                outstandingPerformance.setScore(newOutstandingExcel.getScore());
                outstandingPerformance.setResponsiblePerson(newOutstandingExcel.getResponsiblePerson());
                outstandingPerformance.setReporter(newOutstandingExcel.getReporter());

                boolean liveNewOutstandingParent = isLiveNewOutstandingParent(outstandingPerformance);
                if (liveNewOutstandingParent) {
                    outstandingPerformanceMapper.insert(outstandingPerformance);
                    BaseOutstandingTreeVo baseOutstandingTreeVo = new BaseOutstandingTreeVo();
                    OutstandingPerformanceVo outstandingPerformanceVo = new OutstandingPerformanceVo();

                    BeanUtil.copyProperties(outstandingPerformance, outstandingPerformanceVo);
                    //TODO 获取存下的内容。

                    //

                    mapForParent.put(responsiblePerson, outstandingPerformance.getId());

                } else {
                    unSave.add(newOutstandingExcel);
                }

            } else {
                OutstandingChild outstandingChild = new OutstandingChild();

                //获取projectId
                Integer projectId = mapForParent.get(responsiblePerson);

                if(projectId!=null){
                    outstandingChild.setProjectId(projectId);
                    outstandingChild.setScore(newOutstandingExcel.getScore());
                    outstandingChild.setTeacherName(newOutstandingExcel.getTeacherName());
                    if (isLiveNewOutstandingChild()) {
                        outstandingChildList.add(outstandingChild);
                    }

                }else {
                    unSave.add(newOutstandingExcel);
                }
            }

        }

        //子表满了就批量保存。
        if (outstandingChildList.size() >= BATCH_COUNT) {
            saveNewOutstandingChildData();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("000");
        saveNewOutstandingChildData();
        log.info("解析完成");
    }


    //子表存
    private void saveNewOutstandingChildData() {
        if (outstandingChildList.size() > 0) {
            outstandingChildMapper.insertByBatch(outstandingChildList);
        }
    }

}
